# Copyright (c) 2023, hzmes and contributors
# For license information, please see license.txt

import json
import frappe
from frappe.model.document import Document
from frappe.utils import now, add_to_date, get_date_str, today, to_timedelta

class SRMPublicEmail(Document):
	pass
	# @frappe.whitelist()
	# def queue_email(self):
	# 	try:
	# 		rev_email = frappe.enqueue_doc(self.doctype, self.name, "send_mail")
	# 		return rev_email
	# 	except frappe.NameError:
	# 		pass

	# def send_mail(self):
	# 	# 查找附件
	# 	if self.attachment:
	# 		file_name = frappe.db.get_value('File',{"attached_to_name": self.name, "attached_to_doctype": self.doctype, "attached_to_field": "attachment"})
	# 		#获取文件单据对象
	# 		file_doc = frappe.get_doc('File', file_name)
	# 		#填充发邮件时的附件参数，主要是获取pdf文件二进制内容
	# 		attachments=[{"fname": file_doc.file_name,"fcontent": file_doc.get_content()}]
	# 	# 当前用户frappe.session.user
	# 	rev_email = []
	# 	rev_email_return = []
	# 	rev_email.append(frappe.session.user)
	# 	for row in self.recipient:
	# 		if row.category == '供应商':
	# 			# 不同的选项会改变sql语句的条件
	# 			if row.condition == '二级供应商':
	# 				sql ="""
	# 					SELECT t2.email_address FROM `tabSRM Supplier` t1 JOIN `tabSRM Supplier Contact Sub` t2 on t1.name = t2.parent WHERE t1.managestatus = '二级' AND t2.enable = 1
	# 					UNION ALL
	# 					SELECT t2.email_address FROM `tabSRM Supplier` t1 JOIN `tabSRM Supplier ContactBackgroud Sub` t2 on t1.name = t2.parent WHERE t1.managestatus = '二级' AND t2.enable = 1 """
	# 				r = frappe.db.sql(sql, as_dict=1)
	# 				for i in r:
	# 					if i.email_address and i.email_address not in rev_email:
	# 						rev_email.append(i.email_address)
	# 			if row.condition == '三级供应商':
	# 				sql ="""
	# 					SELECT t2.email_address FROM `tabSRM Supplier` t1 JOIN `tabSRM Supplier Contact Sub` t2 on t1.name = t2.parent WHERE t1.managestatus = '三级' AND t2.enable = 1
	# 					UNION ALL
	# 					SELECT t2.email_address FROM `tabSRM Supplier` t1 JOIN `tabSRM Supplier ContactBackgroud Sub` t2 on t1.name = t2.parent WHERE t1.managestatus = '三级' AND t2.enable = 1 """
	# 				r = frappe.db.sql(sql, as_dict=1)
	# 				for i in r:
	# 					if i.email_address and i.email_address not in rev_email:
	# 						rev_email.append(i.email_address)
	# 			if row.condition == '合格供应商':
	# 				sql ="""
	# 					SELECT t2.email_address FROM `tabSRM Supplier` t1 JOIN `tabSRM Supplier Contact Sub` t2 on t1.name = t2.parent WHERE t1.qualified = 1 AND t2.enable = 1
	# 					UNION ALL
	# 					SELECT t2.email_address FROM `tabSRM Supplier` t1 JOIN `tabSRM Supplier ContactBackgroud Sub` t2 on t1.name = t2.parent WHERE t1.qualified = 1 AND t2.enable = 1 """
	# 				r = frappe.db.sql(sql, as_dict=1)
	# 				for i in r:
	# 					if i.email_address and i.email_address not in rev_email:
	# 						rev_email.append(i.email_address)
	# 			if row.condition == '仅管理员测试':
	# 				rev_email.append('13556209635@139.com', '115259901@qq.com', 'iou198298@163.com')

	# 	rev1 = rev_email[0:100]
	# 	rev2 = rev_email[100:200]
	# 	rev3 = rev_email[200:300]
	# 	rev4 = rev_email[300:400]
	# 	rev5 = rev_email[400:500]
	# 	rev6 = rev_email[500:600]
	# 	rev7 = rev_email[600:700]
	# 	rev8 = rev_email[700:800]
	# 	rev9 = rev_email[800:900]
	# 	rev10 = rev_email[900:1000]
	# 	# rev11 = rev12 = rev13 = rev14 = rev15 = rev16 = rev17 = rev18 = rev19 = rev20 = []
		
	# 	# 根据当前时间计算send_after应该是10小时或者8小时后或者8分钟后
	# 	cur_hours = divmod(to_timedelta(now()).seconds, 3600)[0]
	# 	# send_start = add_to_date(now(), hours=1)
	# 	if cur_hours < 12:
	# 		send_start = add_to_date(now(), hours=10)
	# 	if 12 < cur_hours < 18:
	# 		send_start = add_to_date(now(), hours=8)
	# 	else:
	# 		send_start = add_to_date(now(), minutes=8)
	# 	if len(rev1) > 0:
	# 		self.my_sendmail(recipients=rev1, send_after=add_to_date(send_start, hours=0), attachments=attachments)
	# 	if len(rev2) > 0:
	# 		self.my_sendmail(recipients=rev2, send_after=add_to_date(send_start, hours=1), attachments=attachments)
	# 	if len(rev3) > 0:
	# 		self.my_sendmail(recipients=rev3, send_after=add_to_date(send_start, hours=2), attachments=attachments)
	# 	if len(rev4) > 0:
	# 		self.my_sendmail(recipients=rev4, send_after=add_to_date(send_start, hours=3), attachments=attachments)
	# 	if len(rev5) > 0:
	# 		self.my_sendmail(recipients=rev5, send_after=add_to_date(send_start, hours=4), attachments=attachments)
	# 	if len(rev6) > 0:
	# 		self.my_sendmail(recipients=rev6, send_after=add_to_date(send_start, hours=5), attachments=attachments)
	# 	if len(rev7) > 0:
	# 		self.my_sendmail(recipients=rev7, send_after=add_to_date(send_start, hours=6), attachments=attachments)
	# 	if len(rev8) > 0:
	# 		self.my_sendmail(recipients=rev8, send_after=add_to_date(send_start, hours=7), attachments=attachments)
	# 	if len(rev9) > 0:
	# 		self.my_sendmail(recipients=rev9, send_after=add_to_date(send_start, hours=8), attachments=attachments)
	# 	if len(rev10) > 0:
	# 		self.my_sendmail(recipients=rev10, send_after=add_to_date(send_start, hours=9), attachments=attachments)
	# 	rev_email.append(send_start)
	# 	return json.dumps(rev_email)

	# def my_sendmail(self, recipients, send_after, attachments=None):
	# 	frappe.sendmail(
	# 		recipients=recipients,
	# 		sender="Administrator",
	# 		attachments = attachments if attachments else None,
	# 		reference_doctype=self.doctype,
	# 		reference_name=self.name,
	# 		subject=self.subject,
	# 		message=self.main_body,
	# 		send_after=send_after
	# 	)

@frappe.whitelist()
def send_email_hourly():
	cur_recipients = frappe.db.get_all('Public Email Recipient Items',filters={'sent': 0},fields=['email_address', 'name', 'parent'],order_by='idx',page_length=50)
	if len(cur_recipients) > 0:
		for i in cur_recipients:
			attachments = []
			doc = frappe.get_doc('SRM Public Email', i.parent)
			if doc.is_send == 1:
				# 查找附件 2023-12-05优化: 取消附件发送避免垃圾邮件
				# if doc.attachment:
				# 	file_name = frappe.db.get_value('File',{"attached_to_name": doc.name, "attached_to_doctype": doc.doctype, "attached_to_field": "attachment"})
				# 	#获取文件单据对象
				# 	file_doc = frappe.get_doc('File', file_name)
				# 	#填充发邮件时的附件参数，主要是获取pdf文件二进制内容
				# 	attachments=[{"fname": file_doc.file_name,"fcontent": file_doc.get_content()}]
				subject = doc.subject
				message = doc.main_body
				frappe.db.set_value('Public Email Recipient Items', i.name, {'sent': 1, 'datetime': now()})
				frappe.sendmail(recipients=i.email_address,sender=frappe.session.user,attachments = attachments if attachments else None,subject=subject,message=message,reference_doctype=doc.doctype,reference_name=doc.name)
			else:
				continue
		frappe.sendmail(recipients='13556209635@139.com',sender=frappe.session.user,subject=f'通告邮件{cur_recipients[0].parent}',message='51 once')
